﻿using System;
using System.Net;
using System.Threading.Tasks;
using UMC.Net;

namespace UMC.Host
{

    public abstract class HttpMime : IDisposable
    {

        public abstract int Id { get; }
        public int ActiveTime
        {

            get; set;
        }
        public int TimeOut { protected set; get; } = 20;

        public virtual string Scheme => "http";
        public abstract void OutputFinish();
        public abstract void Write(byte[] buffer, int offset, int count);


        public abstract void Dispose();
        public abstract String Host { get; }
        public abstract String RemoteIpAddress { get; }


        protected abstract void WebSocket(UMC.Net.NetContext context);

        public virtual void PrepareRespone(HttpMimeRequest request)
        {

            this.TimeOut = 300;
            
            var context = new HttpMimeContext(request, new HttpMimeResponse(this, request));

            try
            {
                context.ProcessRequest();
                if (request.IsWebSocket)
                {
                    this.WebSocket(context);
                }
                else
                {
                    context.ProcessAfter();
                }

            }
            catch (Exception ex)
            {
                context.Error(ex);

            }


        }

        public void OutText(int status, string contentType, String text)
        {
            var writer = new TextWriter(this.Write);
            writer.Write($"HTTP/1.1 {status} {HttpStatusDescription.Get(status)}\r\n");
            writer.Write($"Content-Type: {contentType}; charset=utf-8\r\n");
            writer.Write($"Content-Length: {System.Text.Encoding.UTF8.GetByteCount(text)}\r\n");
            writer.Write("Connection: close\r\n");
            writer.Write("Server: Apiumc\r\n\r\n");
            writer.Write(text);
            writer.Flush();
            writer.Close();
            this.Dispose();
        }
        public void OutText(int status, String text)
        {
            this.OutText(status, "text/plain", text);

        }
    }
}

